package ca.uvic.cs.cogz.mapping;

import java.util.ArrayList;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import ca.uvic.cs.cogz.mapping.core.AbstractMapElement;
import edu.stanford.smi.protegex.prompt.operation.Operation;

public class TemporaryMappingManager {
	private ArrayList<Operation> temporaryOperations;
	private ArrayList<ChangeListener> listeners;

	public TemporaryMappingManager() {
		temporaryOperations = new ArrayList<Operation>();
		listeners = new ArrayList<ChangeListener>();
	}

	public void addChangeListener(ChangeListener listener) {
		listeners.add(listener);
	}

	public void addTemporaryMapping(Operation tempOperation) {
		if (!isTemporaryOperation(tempOperation)) {
			temporaryOperations.add(tempOperation);
			fireChangeListeners(tempOperation);
		}
	}

	public Operation getOperationForMapping(AbstractMapElement mapElement) {
		for (int i = 0; i < temporaryOperations.size(); i++) {
			Operation operation = temporaryOperations.get(i);
			if (operation.getArgs().getArg(0).equals(mapElement.getSourceFrame()) && operation.getArgs().getArg(1).equals(mapElement.getTargetFrame())) {
				return operation;
			}
		}

		return null;
	}

	public void removeTemporaryMapping(AbstractMapElement mapElement) {
		for (int i = 0; i < temporaryOperations.size(); i++) {
			Operation operation = temporaryOperations.get(i);
			if (operation.getArgs().getArg(0).equals(mapElement.getSourceFrame()) && operation.getArgs().getArg(1).equals(mapElement.getTargetFrame())) {
				temporaryOperations.remove(i);
				fireChangeListeners(operation);
				i--;
			}
		}
	}

	public void removeTemporaryMapping(Operation tempOperation) {
		temporaryOperations.remove(tempOperation);
		fireChangeListeners(tempOperation);
	}

	public boolean isTemporaryOperation(AbstractMapElement mapElement) {
		Operation operation = getOperationForMapping(mapElement);
		if (operation != null) {
			return temporaryOperations.contains(operation);
		}

		return false;
	}

	public boolean isTemporaryOperation(Operation operation) {
		return temporaryOperations.contains(operation);
	}

	public ArrayList<Operation> getTemporaryMappings() {
		return temporaryOperations;
	}

	private void fireChangeListeners(Operation source) {
		for (ChangeListener listener : listeners) {
			listener.stateChanged(new ChangeEvent(source));
		}
	}
}
